package com.itheima.tliasmanager.aop;

import com.itheima.tliasmanager.mapper.OperateLogMapper;
import com.itheima.tliasmanager.pojo.domain.OperateLog;
import com.itheima.tliasmanager.utils.ApplicationContext;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

//@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.tliasmanager.annotation.Log)")
    public Object recordOperateLog(ProceedingJoinPoint pjp) throws Throwable {

        OperateLog log = new OperateLog();

        log.setOperateTime(LocalDateTime.now());

        log.setClassName(pjp.getTarget().getClass().getName());
        log.setMethodName(pjp.getSignature().getName());
        log.setMethodParams(Arrays.toString(pjp.getArgs()));


        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        log.setCostTime(end-start);
        log.setReturnValue(result +"");

//        String token = request.getHeader("token");
//        Claims claims = JwtUtils.parseJWT(token);
//        Integer id =(Integer) claims.get("id");
        log.setOperateEmpId(ApplicationContext.getEmpId());


        operateLogMapper.insert(log);
        ApplicationContext.clear();
        return result;
    }
}

